package com.inctech.controller.fileResource;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.inctech.interceptor.AuthPassport;
import com.inctech.model.FileResource;
import com.inctech.service.IFileService;

@Controller
@RequestMapping("/fileresource")
public class FileResourceController {
	final Logger logger = LoggerFactory.getLogger(FileResourceController.class);

	@Resource(name = "fileService")
	private IFileService fileService;

	@AuthPassport
	@RequestMapping("/fileindex")
	public String index() {
		return "fileresource/fileindex";
	}

	/**
	 * 分页查询
	 * 
	 * @param page
	 * @param rows
	 * @return
	 */
	@AuthPassport
	@ResponseBody
	@RequestMapping("/selectAllFile")
	public String selectAllFile(int page, int rows, String states, String fileName, String fileType) {
		if (states == null || "".equals(states)) {
			states = "1";
		}
		JSONObject obj = new JSONObject();
		int currentPage = (page == 0) ? 1 : page;// 当前页
		int pageSize = (rows == 0) ? 10 : rows;// 每页显示条数
		int index = (currentPage - 1) * pageSize;// 从第几条开始显示
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("index", index);
		paramMap.put("pageSize", pageSize);
		paramMap.put("states", states);// 文件状态
		paramMap.put("fileName", fileName);// 文件名称
		paramMap.put("fileType", fileType);// 文件类别
		try {
			List<FileResource> fileList = fileService.selectByPage(paramMap);
			String json = JSON.toJSONStringWithDateFormat(fileList, "yyyy-MM-dd HH:mm:ss");
			int total = fileService.getTocal(paramMap);
			obj.put("total", total);
			obj.put("rows", json);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("获取数据出错", e);
		}
		return obj.toString();
	}

	/**
	 * 文件上传 tomcat 配置虚拟路径
	 * 
	 * @param request
	 * @param response
	 * @param fileType
	 *            文件类别
	 * @param purview
	 *            下载权限
	 * @return
	 */
	@AuthPassport
	@ResponseBody
	@RequestMapping("/upload")
	public String upload(HttpServletRequest request, HttpServletResponse response, String fileType,
			String purview) {
		JSONObject obj = new JSONObject();
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request
					.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				int nu = 0;
				FileResource upfile = null;
				// 定义上传路径
				String path = "D:/upload/";
				File parentFile = new File(path);
				if (!parentFile.exists()) {
					parentFile.mkdirs();
				}
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {
					upfile = new FileResource();
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						// 取得当前上传文件的文件名称
						String myFileName = file.getOriginalFilename();
						// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if (myFileName.trim() != "") {
							nu++;
							UUID uuid = UUID.randomUUID();
							// 文件后缀
							String type = myFileName.substring(myFileName.lastIndexOf("."));
							// 重命名上传后的文件名
							String newName = uuid + type;
							// 获取登入用户信息
							HttpSession session = request.getSession();
							String user = (String) session.getAttribute("currentUser");
							upfile.setFileName(myFileName);
							upfile.setFileType(fileType);
							upfile.setCreateDate(new Date());
							upfile.setCreater(user);
							upfile.setPurview(purview);
							upfile.setUrl("/upload/" + newName);
							// 插入数据库
							fileService.insert(upfile);
							// 本地的新文件
							File localFile = new File(path, newName);
							// 将上传文件写入本地文件
							file.transferTo(localFile);
						}
					}
				}
				if (nu == 0) {
					obj.put("success", false);
					obj.put("msg", "请选择上传文件!");
				} else {
					obj.put("success", true);
					obj.put("msg", "上传成功!");
				}
			}
		} catch (Exception e) {
			obj.put("success", false);
			obj.put("msg", "上传失败!");
			logger.error("上传失败!", e);
		}
		return obj.toString();
	}

	/**
	 * 文件下载 路径调用tomcat配置的虚拟路径
	 * 
	 * @param url
	 *            文件路径
	 * @param fileName
	 *            文件名称
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/download")
	public void download(String url, String fileName, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("UTF-8");
		java.io.BufferedInputStream bis = null;
		java.io.BufferedOutputStream bos = null;

		String downLoadPath = url;
		try {
			long fileLength = new File(downLoadPath).length();
			response.setContentType("application/x-msdownload;");
			response.setHeader("Content-disposition",
					"attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
			response.setHeader("Content-Length", String.valueOf(fileLength));
			bis = new BufferedInputStream(new FileInputStream(downLoadPath));
			bos = new BufferedOutputStream(response.getOutputStream());
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bis != null)
				bis.close();
			if (bos != null)
				bos.close();
		}
	}

	/**
	 * 文件删除
	 * 
	 * @param request
	 * @return
	 */
	@AuthPassport
	@ResponseBody
	@RequestMapping("/deleteFile")
	public String deleteFile(HttpServletRequest request) {
		JSONObject obj = new JSONObject();
		String[] fileIds = request.getParameterValues("fileIds[]");
		String[] urls = request.getParameterValues("urls[]");
		String isDelFile = request.getParameter("isDelFile");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			if ("notFile".equals(isDelFile)) {// 普通删除 保留本地文件
				for (int i = 0; i < fileIds.length; i++) {
					paramMap.put("fileId", Integer.parseInt(fileIds[i]));
					paramMap.put("states", "0");// 设为无效状态
					paramMap.put("isdel", null);
					fileService.deleteByPrimaryKey(paramMap);
				}
			} else {// 彻底删除 不保留本地文件
				for (int i = 0; i < urls.length; i++) {
					paramMap.put("fileId", Integer.parseInt(fileIds[i]));
					paramMap.put("states", null);
					paramMap.put("isdel", "0");// 设置文件不存在状态
					fileService.deleteByPrimaryKey(paramMap);
					File localFile = new File(urls[i]);// 获取本地文件
					if (!localFile.exists()) {
						obj.put("success", false);
						obj.put("msg", "删除失败!本地文件不存在!");
						throw new Exception("本地文件不存在!路径：" + urls[i]);
					} else {
						localFile.delete();// 删除本地文件
					}
				}
			}
			obj.put("success", true);
			obj.put("msg", "删除成功!");
		} catch (Exception e) {
			obj.put("success", false);
			obj.put("msg", "删除失败!" + e);
			e.printStackTrace();
		}
		return obj.toString();
	}

	/**
	 * 文件还原
	 * 
	 * @param request
	 * @return
	 */
	@AuthPassport
	@ResponseBody
	@RequestMapping("/fileBack")
	public String fileBack(HttpServletRequest request) {
		JSONObject obj = new JSONObject();
		String[] fileIds = request.getParameterValues("fileIds[]");
		try {
			for (int i = 0; i < fileIds.length; i++) {
				fileService.fileBack(Integer.parseInt(fileIds[i]));
			}
			obj.put("success", true);
			obj.put("msg", "还原成功!");
		} catch (Exception e) {
			obj.put("success", false);
			obj.put("msg", "还原失败!" + e);
			e.printStackTrace();
		}
		return obj.toString();
	}
}
